import {ArgumentMetadata, ClassSerializerInterceptor, PipeTransform} from "@nestjs/common";
import {plainToInstance} from "class-transformer";
import {APP_INTERCEPTOR} from "@nestjs/core";
import {PageQuery} from "../page/PageQuery";
import {ClassConstructor} from "class-transformer/types/interfaces";

/**
 * 全局Dto序列化和反序列化
 */

export const GlobalSerializeProvider = {
    provide: APP_INTERCEPTOR,
    useClass: ClassSerializerInterceptor
}

export class MyDtoSerializePipe implements PipeTransform{

    constructor(private nested?:ClassConstructor<any>) {
    }

    transform(value: any, metadata: ArgumentMetadata): any {
        console.log("Dto序列化和反序列化 is invoked...")
        let {metatype} = metadata;
        let instance = plainToInstance(metatype, value);
        // 分页参数序列化和反序列化
        if (metatype.name == PageQuery.name && this.nested) {
            instance.param = plainToInstance(this.nested, value.param);
        }
        return instance;
    }

}
